package client.invoke;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import service.IInfoService;
import client.link.message.SendMessage;
import client.serial.MethodCallEntity;

@SuppressWarnings("unchecked")
public class ProxyFactory implements InvocationHandler{
    
    private Class<?> clazz;
    private String ip;
    private int port;
    
    public ProxyFactory(String ip, int port, Class<?> clazz) {
        this.ip = ip;
        this.port = port;
        this.clazz = clazz;
    }

    public static <T> T getProxy(String ip,int port,Class<T> clazz){
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), 
                new Class[]{clazz}, new ProxyFactory(ip,port,clazz));
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        MethodCallEntity serial = new MethodCallEntity(clazz.getName(), method.getName(), method.getReturnType().getName(), args);
        SendMessage.sendRequest(serial.getMethodCall(), ip, port);
        return 1;
    }
    
    public static void main(String[] args) {
        IInfoService service = ProxyFactory.getProxy("127.0.0.1",21111,IInfoService.class);
        service.checkUserState("12312312");
    }
    
}
